import { Injectable } from '@nestjs/common';
import { User } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import {
  DeepPartial,
  FindConditions,
  FindManyOptions,
  FindOneOptions,
  Repository,
} from 'typeorm';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly usersRepository: Repository<User>,
  ) {}
  // 查找一条数据
  findOne(id?: number | string): Promise<User>;
  findOne(findConditions?: FindConditions<User>): Promise<User>;
  findOne(options?: FindOneOptions<User>): Promise<User>;
  findOne(findConditions?: any) {
    return this.usersRepository.findOne(findConditions);
  }

  // 通过 ids 查找多条数据
  findByIds(ids: any[], options?: FindManyOptions<User>) {
    return this.usersRepository.findByIds(ids, options);
  }

  // 查询所有数据
  findCount(findManyOptions: FindManyOptions<User>) {
    return this.usersRepository.findAndCount(findManyOptions);
  }

  // 创建用户
  async create(body: DeepPartial<User>): Promise<User> {
    return await this.usersRepository.save(body);
  }

  // 查询所有用户
  findAndCount(query) {
    const getList = this.usersRepository
      .createQueryBuilder('s')
      .select(['s.username', 's.password'])
      .skip(query.size * (query.page - 1))
      .take(query.size)
      .getMany();
    const list = getList;
    return list;
  }

  // 获取单个用户信息
  findById(id) {
    const user = this.usersRepository
      .createQueryBuilder('s')
      .where('s.id=:id', { id })
      .getOne();
    return user;
  }

  // 用户名的模糊查询
  likeByUserName(username, query) {
    const user = this.usersRepository
      .createQueryBuilder('s')
      .where('s.username like :username', { username: `%${username}%` })
      .skip(query.size * (query.page - 1))
      .take(query.size)
      .getMany();
    return user;
  }

  // 修改用户密码
  updatePassword(id, user) {
    const update = this.usersRepository
      .createQueryBuilder()
      .update(User)
      .set({ password: '888888' })
      .where('id =:id', { id })
      .execute();
    return update;
  }

  // 删除指定用户
  deleteById(id) {
    const user = this.usersRepository
      .createQueryBuilder()
      .delete()
      .from(User)
      .where('id = :id', { id: id })
      .execute();
    return user;
  }
}
